package com.runjian.rundo.iot.agent.common.network.tcp.parser;

import java.nio.charset.StandardCharsets;

import com.runjian.rundo.iot.agent.common.network.tcp.config.TcpNetworkProperties;

import cn.hutool.core.util.StrUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;

/**
 * 分隔符解码器
 *
 * @author CaoQingHua
 */
public class DelimitedPayloadParser implements PayloadParser {

    private final TcpNetworkProperties valueObject;

    public DelimitedPayloadParser(TcpNetworkProperties valueObject) {
        this.valueObject = valueObject;
    }

    @Override
    public ByteToMessageDecoder getParser() {
        String delimiter = valueObject.getDelimited().getDelimiter();
        Integer maxSize = valueObject.getDelimited().getMaxSize();
        if (StrUtil.isEmpty(delimiter)) {
            throw new IllegalArgumentException("分隔符不能为空");
        }
        ByteBuf byteBuf = Unpooled.buffer();
        byteBuf.writeBytes(delimiter.getBytes(StandardCharsets.UTF_8));
        return new DelimiterBasedFrameDecoder(maxSize, byteBuf);
    }
}
